<?php

require_once '../vendor/autoload.php'; // 如果使用Composer
// 或者直接引入文件
// require_once '../src/JingdongCallbackSDK.php';

use Jingdong\Callback\JingdongCallbackSDK;

// 配置信息
$config = [
    // 必需参数
    'developer_id' => 'your-developer-id',     // 海博技术服务平台分配的开发者ID
    'secret' => 'your-secret',                 // 签名密钥
    
    // 环境配置
    'environment' => 'test',                   // test, sandbox, prod
    
    // Redis配置（可选，用于防重复）
    'redis_config' => [
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 0,
        'password' => '',                      // 如果Redis有密码
        'timeout' => 3.0
    ],
    
    // 其他配置
    'enable_log' => true,                      // 是否启用日志
    'user_agent' => 'MyApp-JingdongSDK/1.0'   // 自定义User-Agent
];

// 初始化SDK
$sdk = new JingdongCallbackSDK($config);

// 设置自定义日志处理器（可选）
$sdk->setLogger(function($level, $message, $context) {
    $logMessage = sprintf('[%s] [%s] %s', date('Y-m-d H:i:s'), strtoupper($level), $message);
    if (!empty($context)) {
        $logMessage .= ' ' . json_encode($context, JSON_UNESCAPED_UNICODE);
    }
    echo $logMessage . PHP_EOL;
});

// 示例1：基本状态回调
echo "=== 示例1：基本状态回调 ===" . PHP_EOL;

$order = [
    'id' => 12345,
    'platform_order_no' => 'JD202312345678',    // 平台订单号
    'order_no' => 'ORDER_20231201_001',          // 本地订单号
    'jd_store_id' => 'STORE_001',                // 京东门店ID
    'carrier_merchant_id' => 'HBT_JZD',          // 配送商商户ID
    'rider_id' => 1001,                          // 骑手ID
    'rider_name' => '张三',                       // 骑手姓名
    'rider_phone' => '13800138000',              // 骑手手机号
    'rider_lng' => 116.397128,                   // 骑手经度
    'rider_lat' => 39.916527                     // 骑手纬度
];

// 发送"已接单"状态回调
$result = $sdk->sendStatusCallback($order, 20);

if ($result['success']) {
    echo "✅ 状态回调发送成功" . PHP_EOL;
    echo "响应数据: " . json_encode($result['data'], JSON_UNESCAPED_UNICODE) . PHP_EOL;
} else {
    echo "❌ 状态回调发送失败: " . $result['message'] . PHP_EOL;
}

echo PHP_EOL;

// 示例2：包含额外参数的状态回调
echo "=== 示例2：包含额外参数的状态回调 ===" . PHP_EOL;

$extraParams = [
    'riderLng' => 116.407526,          // 实时骑手经度
    'riderLat' => 39.904030,           // 实时骑手纬度
    'orderImages' => [                 // 订单图片
        'pickup' => [
            'https://example.com/image1.jpg',
            'https://example.com/image2.jpg'
        ]
    ]
];

// 发送"已取货"状态回调
$result = $sdk->sendStatusCallback($order, 30, $extraParams);

if ($result['success']) {
    echo "✅ 已取货状态回调发送成功" . PHP_EOL;
} else {
    echo "❌ 已取货状态回调发送失败: " . $result['message'] . PHP_EOL;
}

echo PHP_EOL;

// 示例3：取消订单回调
echo "=== 示例3：取消订单回调 ===" . PHP_EOL;

$cancelParams = [
    'cancelReasonCode' => JingdongCallbackSDK::getCancelReasonCode('CUSTOMER'), // 用户取消
    'cancelReasonDesc' => JingdongCallbackSDK::getCancelReasonDesc('CUSTOMER', '用户临时有事'), // 取消原因描述
    'cancelFee' => 5.00                                                          // 取消费用
];

// 发送取消状态回调
$result = $sdk->sendStatusCallback($order, 99, $cancelParams);

if ($result['success']) {
    echo "✅ 取消订单回调发送成功" . PHP_EOL;
} else {
    echo "❌ 取消订单回调发送失败: " . $result['message'] . PHP_EOL;
}

echo PHP_EOL;

// 示例4：转单回调
echo "=== 示例4：转单回调 ===" . PHP_EOL;

$transferParams = [
    'isTransfer' => true,                    // 标识为转单操作
    'oldRiderId' => 1001,                    // 原骑手ID
    'newRiderId' => 1002,                    // 新骑手ID
    'newRiderName' => '李四',                 // 新骑手姓名
    'newRiderPhone' => '13900139000',        // 新骑手手机号
    'transferReason' => '骑手临时有事转单'     // 转单原因
];

// 发送转单后的"已接单"状态回调
$result = $sdk->sendStatusCallback($order, 20, $transferParams);

if ($result['success']) {
    echo "✅ 转单回调发送成功" . PHP_EOL;
} else {
    echo "❌ 转单回调发送失败: " . $result['message'] . PHP_EOL;
}

echo PHP_EOL;

// 示例5：包含费用信息的完成回调
echo "=== 示例5：包含费用信息的完成回调 ===" . PHP_EOL;

$orderWithFee = $order;
$orderWithFee['fee'] = [
    'actual_amount' => 15.80,     // 实际支付金额
    'toll_fee' => 2.00,           // 过路费
    'waiting_fee' => 1.00,        // 等待费
    'parking_fee' => 0.50         // 停车费
];

// 发送"已送达"状态回调
$result = $sdk->sendStatusCallback($orderWithFee, 50);

if ($result['success']) {
    echo "✅ 已送达回调发送成功" . PHP_EOL;
} else {
    echo "❌ 已送达回调发送失败: " . $result['message'] . PHP_EOL;
}

echo PHP_EOL;

// 示例6：连通性测试
echo "=== 示例6：连通性测试 ===" . PHP_EOL;

$connectivity = $sdk->testConnectivity();

echo "DNS解析: " . ($connectivity['dns']['success'] ? "✅ 成功" : "❌ 失败") . PHP_EOL;
echo "  主机: " . $connectivity['dns']['host'] . " => " . $connectivity['dns']['ip'] . PHP_EOL;

echo "端口连通: " . ($connectivity['port']['success'] ? "✅ 成功" : "❌ 失败") . PHP_EOL;
echo "  端口: " . $connectivity['port']['host'] . ":" . $connectivity['port']['port'] . PHP_EOL;
if (!$connectivity['port']['success'] && isset($connectivity['port']['error'])) {
    echo "  错误: " . $connectivity['port']['error'] . PHP_EOL;
}

echo "HTTP请求: " . ($connectivity['http']['success'] ? "✅ 成功" : "❌ 失败") . PHP_EOL;
echo "  状态码: " . $connectivity['http']['http_code'] . PHP_EOL;
if (!$connectivity['http']['success'] && isset($connectivity['http']['curl_error'])) {
    echo "  错误: " . $connectivity['http']['curl_error'] . PHP_EOL;
}

echo PHP_EOL;

// 示例7：状态转换工具
echo "=== 示例7：状态转换工具 ===" . PHP_EOL;

$localStatuses = ['0', '10', '20', '25', '30', '40', '50', '99'];

foreach ($localStatuses as $localStatus) {
    $jdStatus = JingdongCallbackSDK::convertLocalStatusToJingdongStatus($localStatus);
    echo "本地状态 {$localStatus} => 京东状态 {$jdStatus}" . PHP_EOL;
}

echo PHP_EOL;

// 示例8：取消原因码工具
echo "=== 示例8：取消原因码工具 ===" . PHP_EOL;

$roles = ['ADMIN', 'MERCHANT', 'CUSTOMER', 'SYSTEM', 'RIDER', 'CARRIER'];

foreach ($roles as $role) {
    $reasonCode = JingdongCallbackSDK::getCancelReasonCode($role);
    $reasonDesc = JingdongCallbackSDK::getCancelReasonDesc($role);
    echo "角色 {$role} => 取消码 {$reasonCode} ({$reasonDesc})" . PHP_EOL;
}

echo PHP_EOL . "示例运行完成！" . PHP_EOL;
